package com.qiwx.pigeon.fragment.produce;

import android.graphics.Color;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.DateTimeUtils;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.activity.MainActivity;
import com.qiwx.pigeon.adapter.chart.ChartDataAdapter;
import com.qiwx.pigeon.base.BaseMVPFragment;
import com.qiwx.pigeon.data.params.ChartParam;
import com.qiwx.pigeon.data.vo.ChartFertilizedBeanVo;
import com.qiwx.pigeon.data.vo.SummaryCL;
import com.qiwx.pigeon.data.vo.SummaryDaliy;
import com.qiwx.pigeon.listviewitems.ChartItem;
import com.qiwx.pigeon.listviewitems.LineChartItem;
import com.qiwx.pigeon.listviewitems.PieChartItem;
import com.qiwx.pigeon.presenter.DataChartPresenter;
import com.qiwx.pigeon.viewinterface.IDataChartView;
import com.qiwx.pigeon.widget.SelectDatePopWindow;

import org.angmarch.views.NiceSpinner;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * @description
 * @Author qiwx
 * @Date 2020-05-29 09:31
 * 数据统计表
 **/
public class DataChartFragment extends BaseMVPFragment<IDataChartView, DataChartPresenter> implements IDataChartView {

    ChartParam chartParam = new ChartParam();
    @BindView(R.id.listView1)
    ListView listView1;
    ArrayList<ChartItem> list = new ArrayList<>();
    ChartDataAdapter adapter;
    @BindView(R.id.spinner_wh)
    NiceSpinner spinnerWh;
    @BindView(R.id.txt_start_date)
    TextView txtStartDate;
    @BindView(R.id.txt_end_date)
    TextView txtEndDate;
    @BindView(R.id.lin_query_tools_date)
    LinearLayout linQueryToolsDate;
    @BindView(R.id.btn_condition)
    Button btnCondition;
    @BindView(R.id.btn_query)
    Button btnQuery;
    @BindView(R.id.rel_query_tools_top)
    RelativeLayout relQueryToolsTop;

    ChartFertilizedBeanVo chartFertilizedBeanVo = null;
    SummaryCL summaryCL = null;
    List<SummaryDaliy> summaryDaliy = null;
    private String startDate;
    private String endDate;
    int query_wh_id;//


    @Override
    public void initAfterOnCreate() {
        super.initAfterOnCreate();
        initView();
        Collections.synchronizedList(list);
        adapter = new ChartDataAdapter(getActivity(), list);
        listView1.setAdapter(adapter);

        loadData();
    }

    private void initView() {
        spinnerWh.setVisibility(View.GONE);
        btnCondition.setVisibility(View.GONE);
        initDate();

    }

    private void initDate() {
        Date currentDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        int max = calendar.getActualMaximum(Calendar.DATE);
//        int min = calendar.getActualMinimum(Calendar.DATE);
        int currentDay = calendar.get(Calendar.DATE);
        Date d1 = DateTimeUtils.addDay(currentDate, (max - currentDay));
        Date d2 = DateTimeUtils.addDay(currentDate, (1 - currentDay));
        txtStartDate.setText(DateTimeUtils.date2String(d2));
        txtEndDate.setText(DateTimeUtils.date2String(d1));
        startDate = txtStartDate.getText().toString();
        endDate = txtEndDate.getText().toString();

    }

    @Override
    public void onReFreshData() {
        super.onReFreshData();
        if(mPresenter==null)
            return;
        loadData();
    }

    private void loadData() {
        int days = DateTimeUtils.differentDays(startDate, endDate);
        if (days < 0) {
            MyToast.showShort("结束日期不能早于开始日期");
            return;
        }
        query_wh_id = MainActivity.wh_id;
        chartParam.setWh_id(query_wh_id);
        chartParam.setStart_date(startDate);
        chartParam.setEnd_date(endDate);
        mPresenter.queryChartFertilized(chartParam);
        mPresenter.queryChartCK(chartParam);
        mPresenter.queryChartDaliy(chartParam);
        chartFertilizedBeanVo = null;
        summaryDaliy = null;
        summaryCL = null;
        list.clear();
    }

    @Override
    public DataChartPresenter createPresenter() {
        return new DataChartPresenter(new WeakReference(this));
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_data_chart;
    }

    @Override
    public void onSuccess(ChartFertilizedBeanVo data) {
//        Log.e("TAG", "成功" + data.getBad_amount());
        chartFertilizedBeanVo = data;
        addData();


    }

    @Override
    public void onSuccess(SummaryCL data) {
        summaryCL = data;
        addData();
    }

    @Override
    public void onSuccess(List<SummaryDaliy> data) {
        summaryDaliy = data;
        addData();

    }

    private void addData() {
        if (summaryCL != null &&
                chartFertilizedBeanVo != null &&
                summaryDaliy != null
        ) {
            initCDChartData(chartFertilizedBeanVo);
            initShouJChartData(chartFertilizedBeanVo);
            initCKChartData(summaryCL);
            initLayEggChartData(summaryDaliy);
            adapter.notifyDataSetChanged();
        }
    }
    public void changeData() {
        if (query_wh_id != MainActivity.wh_id) {
            loadData();
        }
    }

    //初始化出壳
    private void initCKChartData(SummaryCL data) {
        int ck_amount = data.getCk_amount();
        int death_amount = data.getDeath_amount();

        ArrayList<PieEntry> entries = new ArrayList<>();

        PieEntry cd = new PieEntry(ck_amount * 1.0f, "出壳");
        PieEntry lose = new PieEntry(death_amount * 1.0f, "死亡");
//        PieEntry breaken = new PieEntry(breaken_amount * 1.0f, "破蛋");
//        PieEntry wd = new PieEntry(wd_amount * 1.0f, "其他");
        entries.add(cd);
        entries.add(lose);
//        entries.add(breaken);
//        entries.add(wd);

        PieDataSet d = new PieDataSet(entries, "");
        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(getResources().getColor(R.color.egg_cd_color));
        colors.add(getResources().getColor(R.color.egg_bad_color));
        d.setColors(colors);
//        d.setColors(ColorTemplate.VORDIPLOM_COLORS);
        // space between slices
        d.setSliceSpace(2f);
        PieData pieData = new PieData(d);
        PieChartItem pieChartItem = new PieChartItem(pieData, getActivity(), "乳鸽出栏统计");
        list.add(pieChartItem);

    }

    //初始化下蛋和损失数据
    private void initLayEggChartData(List<SummaryDaliy> data) {
//        int days = DateTimeUtils.differentDays(startDate,endDate);

        ArrayList<Entry> lay_datas = new ArrayList<>();//下蛋量
        ArrayList<Entry> lose_datas = new ArrayList<>();//损失量
        for (int i = 0; i < data.size(); i++) {
            SummaryDaliy sd = data.get(i);
            int lay_amount = sd.getLay_amount();
            lay_datas.add(new Entry(i, lay_amount));
            int lose_amount = sd.getBfd_amount();
            lose_amount += sd.getBreaken_amount();
            lose_amount += sd.getWd_amount();
            lose_datas.add(new Entry(i, lose_amount));
        }

        LineDataSet d1 = new LineDataSet(lay_datas, "下蛋量");
        d1.setLineWidth(2.5f);
        d1.setCircleRadius(4.5f);
        d1.setHighLightColor(Color.rgb(244, 117, 117));
        d1.setDrawValues(true);
        d1.setValueFormatter(new myIntFormat());
        LineDataSet d2 = new LineDataSet(lose_datas, "损失量");
        d2.setLineWidth(2.5f);
        d2.setCircleRadius(4.5f);
        d2.setHighLightColor(Color.rgb(244, 117, 117));
        d2.setColor(ColorTemplate.VORDIPLOM_COLORS[0]);
        d2.setCircleColor(ColorTemplate.VORDIPLOM_COLORS[0]);
        d2.setDrawValues(true);
        d2.setValueFormatter(new myIntFormat());

        ArrayList<ILineDataSet> sets = new ArrayList<>();
        sets.add(d1);
        sets.add(d2);
        LineChartItem pieChartItem = new LineChartItem(new LineData(sets), getActivity(), summaryDaliy);
        list.add(pieChartItem);

    }

    class myIntFormat extends ValueFormatter {
        @Override
        public String getFormattedValue(float value) {
            int n = (int) value;
            return n + "";
        }
    }

    //初始化查蛋数据
    private void initCDChartData(ChartFertilizedBeanVo data) {
        int lay_amount = data.getLay_egg_amount();
        int bad_amount = data.getBad_amount();
        int breaken_amount = data.getBreaken_amount();
        int wd_amount = data.getWd_amount();
        int lose_amount = bad_amount + breaken_amount + wd_amount;
        int cd_amount = lay_amount - lose_amount;
        ArrayList<PieEntry> entries = new ArrayList<>();

        PieEntry cd = new PieEntry(cd_amount * 1.0f, "查蛋");
        PieEntry lose = new PieEntry(bad_amount * 1.0f, "损失");
//        PieEntry breaken = new PieEntry(breaken_amount * 1.0f, "破蛋");
//        PieEntry wd = new PieEntry(wd_amount * 1.0f, "其他");
        entries.add(cd);
        entries.add(lose);
//        entries.add(breaken);
//        entries.add(wd);
        PieDataSet d = new PieDataSet(entries, "");
        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(getResources().getColor(R.color.egg_cd_color));
        colors.add(getResources().getColor(R.color.egg_bad_color));
        colors.add(getResources().getColor(R.color.egg_breakdn_color));
        colors.add(getResources().getColor(R.color.egg_wd_color));
        d.setColors(colors);
//        d.setColors(ColorTemplate.VORDIPLOM_COLORS);
        // space between slices
        d.setSliceSpace(2f);
        PieData pieData = new PieData(d);
        PieChartItem pieChartItem = new PieChartItem(pieData, getActivity(), "查蛋");
        list.add(pieChartItem);
    }

    //初始化受精数据
    private void initShouJChartData(ChartFertilizedBeanVo data) {
        //受精率 无精率 死精率
        int shouj_amount = data.getShouj2() * 2 + data.getShouj1() + data.getShou2si1() + data.getShou2wuj1();
        int wuj_amount = data.getWuj2() * 2 + data.getWuj1() + data.getWu2si1() + data.getShou2wuj1();
        int sij_amount = data.getSij2() * 2 + data.getSij1() + data.getWu2si1() + data.getShou2si1();
        ArrayList<PieEntry> entries = new ArrayList<>();

        PieEntry shouJ = new PieEntry(shouj_amount * 1.0f, "受精");
        PieEntry wuJ = new PieEntry(wuj_amount * 1.0f, "无精");
        PieEntry siJ = new PieEntry(sij_amount * 1.0f, "死精");
        entries.add(shouJ);
        entries.add(wuJ);
        entries.add(siJ);

        PieDataSet d = new PieDataSet(entries, "");
        ArrayList<Integer> colors = new ArrayList<Integer>();
        colors.add(getResources().getColor(R.color.egg_shouj_color));
        colors.add(getResources().getColor(R.color.egg_wuj_color));
        colors.add(getResources().getColor(R.color.egg_sij_color));
        d.setColors(colors);
//        d.setColors(ColorTemplate.VORDIPLOM_COLORS);
        // space between slices
        d.setSliceSpace(2f);
        PieData pieData = new PieData(d);
        PieChartItem pieChartItem = new PieChartItem(pieData, getActivity(), "受精率");
        list.add(pieChartItem);
    }

    @Override
    protected void onSelectDate(int type, String content) {
        if (type == 0) {
            startDate = content;
            txtStartDate.setText(startDate);
        } else {
            endDate = content;
            txtEndDate.setText(endDate);
        }
    }

    @Override
    public void onFailed(String error) {

    }

    @OnClick({R.id.txt_start_date, R.id.txt_end_date, R.id.btn_query})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_start_date:
                selectDate("2018-01", 0);
//                selectStartValiDate();
                break;
            case R.id.txt_end_date:
//                showSelectDate("开始日期");
                selectDate(txtStartDate.getText().toString(), 1);

//                selectEndValiDate(txtStartDate.getText().toString());
                break;
            case R.id.btn_query:
                loadData();
                break;
        }
    }
}
